package com.zheng.oa.admin.controller.wc;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zheng.common.base.BaseController;
import com.zheng.common.util.CamelUnderlineConverter;
import com.zheng.common.util.Pagination;
import com.zheng.common.util.PoiUtil;
import com.zheng.oa.common.constant.OaResult;
import com.zheng.oa.common.constant.OaResultConstant;
import com.zheng.oa.common.constant.enums.OaStatus;
import com.zheng.oa.common.constant.enums.PlanTimeType;
import com.zheng.oa.common.constant.enums.PlanType;
import com.zheng.upms.dao.model.UpmsOrganization;
import com.zheng.upms.dao.model.UpmsUser;
import com.zheng.upms.rpc.api.UpmsApiService;
import com.zheng.upms.rpc.api.UpmsOrganizationService;
import com.zheng.wc.dao.model.WcPlan;
import com.zheng.wc.rpc.api.WcPlanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.apache.zookeeper.data.Id;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2018/3/30
 * Time: 9:28
 */
@Controller
@Api(value = "部门年度计划管理", description = "部门年度计划管理")
@RequestMapping("/oa/wc/deptYearPlan")
public class WcDeptYearPlanController extends BaseController {
    @Autowired
    private WcPlanService planService;
    @Autowired
    private UpmsOrganizationService organizationService;
    @Autowired
    private UpmsApiService apiService;

    @ApiOperation(value = "部门年计划管理")
    @RequiresPermissions("oa:wc:deptYearPlan:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        List<UpmsOrganization> organizations = organizationService.selectList(null);
        model.addAttribute("depts", JSON.toJSON(organizations));
        return "/manage/wc/deptYearPlan/index.jsp";
    }

    @ApiOperation(value = "部门年计划列表")
    @RequiresPermissions("oa:wc:deptYearPlan:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(@RequestParam(required = false, defaultValue = "1", value = "pageNumber") int pageNumber,
                       @RequestParam(required = false, defaultValue = "10", value = "pageSize") int pageSize,
                       @RequestParam(required = false, value = "sortName") String sortName,
                       @RequestParam(required = false, value = "sortOrder") String sortOrder,
                       WcPlan plan) {
        plan.getSqlMap().put("sql",apiService.sqlDataScopeFilter(getUsername(), "wp", "uu"));
        plan.setTimeType(PlanTimeType.YEAR_PLAN.getKey());
        plan.setPlanType(PlanType.DEPARTMENT.getKey());
        plan.setStatus(OaStatus.NORMAL.getKey());
        plan.setPagination(new Pagination(pageNumber, pageSize, sortOrder, sortName));
        List<Map<String, Object>> rows = planService.selectPlanMaps(plan);
        Integer total = planService.selectPlanMapsCount(plan);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "新增部门年度计划")
    @RequiresPermissions("oa:wc:deptYearPlan:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {
        int year = LocalDate.now().getYear();
        String username = getUsername();
        UpmsOrganization organization = apiService.selectUpmsOrganizationByUsername(username);
        model.addAttribute("organization", JSON.toJSON(organization));
        model.addAttribute("year", year);
        return "/manage/wc/deptYearPlan/create.jsp";
    }

    @ApiOperation(value = "新增部门年度计划")
    @RequiresPermissions("oa:wc:deptYearPlan:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(@RequestBody WcPlan plan) throws Exception {
        String username = getUsername();
        UpmsUser upmsUser = apiService.selectUpmsUserByUsername(username);
        plan.setCuser(upmsUser.getUserId());
        plan.setCorganization(upmsUser.getOrganizationId());
        plan.setCtime(new Date());
        plan.setReadCount(0);
        plan.setStatus(OaStatus.NORMAL.getKey());
        plan.setPlanType(PlanType.DEPARTMENT.getKey());
        plan.setTimeType(PlanTimeType.YEAR_PLAN.getKey());
        try {
            planService.insert(plan);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "修改部门年度计划")
    @RequiresPermissions("oa:wc:deptYearPlan:update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(Model model, Integer id) {
        WcPlan plan = planService.selectById(id);
        model.addAttribute("plan", JSON.toJSON(plan));
        return "/manage/wc/deptYearPlan/update.jsp";
    }

    @ApiOperation(value = "修改部门年度计划")
    @RequiresPermissions("oa:wc:deptYearPlan:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@RequestBody WcPlan plan) throws Exception {
        try {
            planService.updateById(plan);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "删除部门年度计划")
    @RequiresPermissions("oa:wc:deptYearPlan:delete")
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
        try {
            planService.deletePlans(ids);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "导出部门年度计划")
    @RequiresPermissions("oa:wc:deptYearPlan:export")
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void export(WcPlan plan, HttpServletResponse response) throws Exception {
        plan.setTimeType(PlanTimeType.YEAR_PLAN.getKey());
        plan.setPlanType(PlanType.DEPARTMENT.getKey());
        plan.setStatus(OaStatus.NORMAL.getKey());

        String title = "部门年度计划";
        Integer organizationId = plan.getDeptId();
        if (null != organizationId) {
            UpmsOrganization organization = organizationService.selectById(organizationId);
            if (null != organization) {
                String name = organization.getName();
                title = name + title;
            }
        }
        Integer year = plan.getPlanYear();
        if (null != year) {
            title = year + "年" + title;
        }
        plan.getSqlMap().put("sql",apiService.sqlDataScopeFilter(getUsername(), "wp", "uu"));
        List<Map<String, Object>> plans = planService.selectPlanMaps(plan);
        List<ExcelExportEntity> entities = new ArrayList<>();
        ExcelExportEntity entity = new ExcelExportEntity();
        entity.setKey("plan_name");
        entity.setName("计划名称");
        entities.add(entity);
        entity = new ExcelExportEntity();
        entity.setKey("plan_detail");
        entity.setName("计划详情");
        entities.add(entity);
        entity = new ExcelExportEntity();
        entity.setKey("plan_year");
        entity.setName("计划年份");
        entities.add(entity);
        entity = new ExcelExportEntity();
        entity.setKey("remark");
        entity.setName("备注");
        entities.add(entity);
        entity = new ExcelExportEntity();
        entity.setKey("realname");
        entity.setName("创建人姓名");
        entities.add(entity);
        PoiUtil.export(response, plans, entities, title);
    }

    @RequiresPermissions("oa:wc:deptYearPlan:import")
    @RequestMapping(value = "/import", method = RequestMethod.GET)
    public String doImport() {
        return "/manage/wc/deptYearPlan/import.jsp";
    }

    @RequiresPermissions("oa:wc:deptYearPlan:import")
    @ResponseBody
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public Object doImport(@RequestParam("file") MultipartFile file) {
        //todo 导入excel 中的部门 先判定部门权限
        ImportParams params = new ImportParams();
        String username = getUsername();
        UpmsUser upmsUser = apiService.selectUpmsUserByUsername(username);
        JSONObject data = new JSONObject();
        try {
            List<Map<String, Object>> maps = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, params);
            JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(maps));
            JSONArray planArray = new JSONArray();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String planName = jsonObject.getString("计划名称");
                String planYear = jsonObject.getString("计划年份");
                String organizationName = jsonObject.getString("部门");
                if (StringUtils.isBlank(planName)) {
                    continue;
                }
                if (StringUtils.isBlank(planYear)) {
                    continue;
                }
                if (StringUtils.isBlank(organizationName)) {
                    continue;
                }
                EntityWrapper<UpmsOrganization> entityWrapper = new EntityWrapper<>();
                entityWrapper.where("name='" + organizationName + "'");
                UpmsOrganization organization = organizationService.selectOne(entityWrapper);
                jsonObject.put("deptId", organization.getOrganizationId());
                jsonObject.put("planName", planName);
                jsonObject.put("planDetail", jsonObject.getString("计划详情"));
                jsonObject.put("planYear", planYear);
                jsonObject.put("remark", jsonObject.getString("备注"));
                jsonObject.put("status", OaStatus.NORMAL.getKey());
                jsonObject.put("timeType", PlanTimeType.YEAR_PLAN.getKey());
                jsonObject.put("planType", PlanType.DEPARTMENT.getKey());
                jsonObject.put("ctime", new Date());
                jsonObject.put("cuserId", upmsUser.getUserId());
                planArray.add(jsonObject);
            }
            List<WcPlan> wcPlans = planArray.toJavaList(WcPlan.class);
            data.put("count", wcPlans.size());
            if (wcPlans.size() > 0) {
                planService.insertBatch(wcPlans);
            }
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, "导入失败");
        }
        return new OaResult(OaResultConstant.SUCCESS, data);
    }

    @ApiOperation(value = "阅读年计划")
    @RequiresPermissions("oa:wc:deptYearPlan:read")
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(Integer id, Model model) {
        Map<String, Object> map = planService.selectPlan(id);
        WcPlan plan = new WcPlan();
        plan.setId(id);
        Integer readCount = Integer.parseInt(map.getOrDefault("readCount", 0).toString());
        readCount = readCount + 1;
        plan.setReadCount(readCount);
        map.put("readCount", readCount);
        planService.updateById(plan);
        model.addAttribute("plan", JSON.toJSON(map));
        return "/manage/wc/deptYearPlan/view.jsp";
    }
}
